package oa.hleast.xswl.controller.admin.oms;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import oa.hleast.common.result.Result;
import oa.hleast.xswl.mapper.oms.OmsOrderRefundMapper;
import oa.hleast.xswl.pojo.bo.OrderBO;
import oa.hleast.xswl.pojo.domain.OmsOrderRefund;
import oa.hleast.xswl.pojo.domain.oms.OmsOrder;
import oa.hleast.xswl.pojo.domain.oms.OmsOrderComment;
import oa.hleast.xswl.pojo.domain.oms.OmsOrderDelivery;
import oa.hleast.xswl.pojo.domain.oms.OmsOrderItem;
import oa.hleast.xswl.pojo.dto.MemberDTO;
import oa.hleast.xswl.pojo.dto.UmsUserDto;
import oa.hleast.xswl.pojo.form.OmsOrderCommentReplyForm;
import oa.hleast.xswl.pojo.vo.oms.OmsOrderRefundVo;
import oa.hleast.xswl.pojo.vo.oms.OmsRefundOrderVo;
import oa.hleast.xswl.service.IUmsUserService;
import oa.hleast.xswl.service.oms.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


/**
 * @author 00209
 * @email dz@hleast.com
 * @date 2021/04/12
 */
@Api(tags = "【系统管理】订单服务")
@RestController("AdminOrderController")
@RequestMapping("/api.admin/v1/orders")
@Slf4j
@AllArgsConstructor
public class OrderController {

    private IOrderService orderService;
    private IOrderItemService orderItemService;
    private IUmsUserService memberFeignService;
    private IOrderDeliveryService orderDeliveryService;
    private final OmsOrderCommentService commentService;
    private final OmsOrderCommentReplyService commentReplyService;
    private final OmsOrderRefundMapper refundMapper;
    private final OmsOrderRefundService refundService;

    @ApiOperation("商家查看订单列表")
    @GetMapping("/orderListByStore")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "1", value = "页码", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "limit", defaultValue = "10", value = "每页数量", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "orderSn", value = "订单编号", paramType = "query", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "status", value = "订单状态 101->待付款；102->用户取消；103->系统取消；201->已付款；202->申请退款；203->已退款；301->待发货；401->已发货；501->用户收货；502->系统收货；901->已完成】", paramType = "query", dataType = "Integer", dataTypeClass = Integer.class)
    })
    public Result<List<OmsOrder>> orderListByStore(@RequestParam(defaultValue = "1") Long page,
                                                   @RequestParam(defaultValue = "10") Long limit,
                                                   @RequestParam(required = false) String orderSn,
                                                   @RequestParam(required = false) Integer status) {
        IPage<OmsOrder> result = orderService.orderListByStore(page, limit, orderSn, status);


        return Result.success(result.getRecords(), result.getTotal());
    }

    @ApiOperation("管理员查看订单列表")
    @GetMapping("/orderListByAdmin")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "1", value = "页码", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "limit", defaultValue = "10", value = "每页数量", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "orderSn", value = "订单编号", paramType = "query", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "status", value = "订单状态", paramType = "query", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "storeId", value = "商家id", paramType = "query", dataType = "Long", dataTypeClass = Long.class)
    })
    public Result orderListByAdmin(@RequestParam(defaultValue = "1") Long page,
                                   @RequestParam(defaultValue = "10") Long limit,
                                   @RequestParam(required = false) String orderSn,
                                   @RequestParam(required = false) Integer status,
                                   Long storeId) {
        IPage<OmsOrder> result = orderService.orderListByAdmin(page, limit, orderSn, status, storeId);

        return Result.success(result.getRecords(), result.getTotal());
    }

    @ApiOperation("商家查看申请退款订单列表")
    @GetMapping("/refundOrderListByStore")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "1", value = "页码", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "limit", defaultValue = "10", value = "每页数量", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "orderSn", value = "订单编号", paramType = "query", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "selectStatus", value = "筛选状态 1退款申请中 2退款完成 默认为退款申请中", paramType = "query", dataType = "String", dataTypeClass = String.class),
    })
    public Result<List<OmsRefundOrderVo>> refundOrderListByStore(@RequestParam(defaultValue = "1") Long page,
                                                                 @RequestParam(defaultValue = "10") Long limit,
                                                                 @RequestParam(required = false) String orderSn,
                                                                 @RequestParam(defaultValue = "1") Integer selectStatus) {
        IPage<OmsRefundOrderVo> result = orderService.refundOrderListByStore(page, limit, orderSn, selectStatus);


        return Result.success(result.getRecords(), result.getTotal());
    }

    @ApiOperation("管理员查看退款申请订单列表")
    @GetMapping("/refundOrderListByAdmin")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "1", value = "页码", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "limit", defaultValue = "10", value = "每页数量", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "orderSn", value = "订单编号", paramType = "query", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "storeId", value = "商家id", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "selectStatus", value = "筛选状态 1退款申请中 2退款完成 默认为退款申请中", paramType = "query", dataType = "String", dataTypeClass = String.class)
    })
    public Result<List<OmsRefundOrderVo>> refundOrderListByAdmin(@RequestParam(defaultValue = "1") Long page,
                                                                 @RequestParam(defaultValue = "10") Long limit,
                                                                 @RequestParam(required = false) String orderSn,
                                                                 @RequestParam(required = false) Long storeId,
                                                                 @RequestParam(defaultValue = "1") Integer selectStatus) {


        IPage<OmsRefundOrderVo> result = orderService.refundOrderListByAdmin(page, limit, orderSn, storeId, selectStatus);


        return Result.success(result.getRecords(), result.getTotal());
    }

    @ApiOperation(value = "订单详情", httpMethod = "GET")
    @ApiImplicitParam(name = "id", value = "订单id", required = true, paramType = "path", dataType = "Long", dataTypeClass = Long.class)
    @GetMapping("/{id}")
    public Result detail(@PathVariable Long id) {
        OrderBO orderBO = new OrderBO();
        // 订单
        OmsOrder order = orderService.getById(id);

        // 订单明细
        List<OmsOrderItem> orderItems = orderItemService.list(
                new LambdaQueryWrapper<OmsOrderItem>().eq(OmsOrderItem::getOrderId, id)
        );
        orderItems = Optional.ofNullable(orderItems).orElse(new ArrayList<>());

        // 会员明细
        UmsUserDto member = memberFeignService.getUserDtoById(order.getMemberId());
        MemberDTO memberDTO = new MemberDTO();
        BeanUtil.copyProperties(member, memberDTO);
        orderBO.setOrder(order).setOrderItems(orderItems).setMember(memberDTO);

        OmsOrderDelivery omsOrderDelivery = orderDeliveryService.getOne(new LambdaQueryWrapper<OmsOrderDelivery>().eq(OmsOrderDelivery::getOrderId, id));
        orderBO.setOmsOrderDelivery(omsOrderDelivery);

        // 退款售后申请信息 只支持单订单单商品
        OmsOrderRefundVo refundVo = getOrderRefund(order.getId(), orderItems.get(0).getId());

        OmsOrderRefundVo orderRefundVo = refundService.getDetail(order.getId(), orderItems.get(0).getId());
        orderBO.setOrderRefund(orderRefundVo);

        return Result.success(orderBO);
    }


    private OmsOrderRefundVo getOrderRefund(Long orderId, Long orderItemId) {

        List<OmsOrderRefund> omsOrderRefundList = refundMapper.selectList(new LambdaQueryWrapper<OmsOrderRefund>()
                .eq(OmsOrderRefund::getOrderId, orderId)
                .eq(OmsOrderRefund::getOrderItemId, orderItemId)
                .last("limit 1"));
        if (CollectionUtils.isEmpty(omsOrderRefundList) || omsOrderRefundList.size() < 1) {
            return null;
        }

        OmsOrderRefund omsOrderRefund = omsOrderRefundList.get(0);
        OmsOrderRefundVo vo = new OmsOrderRefundVo();
        BeanUtil.copyProperties(omsOrderRefund, vo);


        return vo;
    }


    @ApiOperation("发货")
    @PostMapping("/{orderId}/_deliver")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单Id", paramType = "path", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "deliveryCompany", value = "快递公司", paramType = "query", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "deliverySn", value = "快递单号", paramType = "query", dataType = "String", dataTypeClass = String.class)
    })
    public Result<Boolean> deliver(@PathVariable Long orderId, String deliveryCompany, String deliverySn) {
        Boolean result = orderService.deliver(orderId, deliveryCompany, deliverySn);
        return Result.success(result);
    }


    @ApiOperation("订单物流查询")
    @PostMapping("/{orderId}/_findDelivery")
    @ApiImplicitParam(name = "orderId", value = "订单ID", paramType = "path", dataType = "Long", dataTypeClass = Long.class)
    public Result findDelivery(@PathVariable Long orderId) {
        String result = orderService.findDelivery(orderId);
        return Result.success(result);
    }


    /**
     * 商品评论审核列表
     */
    @ApiOperation("商品评论审核列表")
    @GetMapping("/findComment")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "limit", value = "", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "reviewStatus", value = "审核状态 0待审核 10审核通过 11审核驳回", paramType = "query", dataType = "Long", dataTypeClass = Long.class)
    })
    public Result<List<OmsOrderComment>> findComment(@RequestParam Integer page, @RequestParam Integer limit, Integer reviewStatus) {
        IPage<OmsOrderComment> result = commentService.findComment(page, limit, reviewStatus);
        return Result.success(result.getRecords(), result.getTotal());
    }


    /**
     * 审核通过or审核驳回
     */
    @ApiOperation("商品评论审核通过or审核驳回")
    @GetMapping("/commentReview")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "remark", value = "", paramType = "query", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "reviewStatus", value = "审核状态 0待审核 10审核通过 11审核驳回", paramType = "query", dataType = "Long", dataTypeClass = Long.class)
    })
    public Result commentReview(@RequestParam Long id, @RequestParam Integer reviewStatus, String remark) {
        Boolean result = commentService.reviewComment(id, reviewStatus, remark);
        return Result.judge(result);
    }


    /**
     * 商家查看商品评论列表
     *
     * @param page         当前页
     * @param limit        每页条数
     * @param spuNo        商品编号
     * @param reviewStatus 审核状态 0待审核 10审核通过 11审核驳回
     * @return
     */
    @ApiOperation("商家查看商品评论列表")
    @GetMapping("/findCommentReview")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "limit", value = "", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "spuNo", value = "商品编号", paramType = "query", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "reviewStatus", value = "审核状态 0待审核 10审核通过 11审核驳回", paramType = "query", dataType = "Long", dataTypeClass = Long.class)
    })
    public Result<List<OmsOrderComment>> findCommentReview(@RequestParam Integer page, @RequestParam Integer limit,
                                                           String spuNo, Integer reviewStatus) {

        IPage<OmsOrderComment> result = commentService.findCommentReviewForStore(page, limit, spuNo, reviewStatus);
        return Result.success(result.getRecords(), result.getTotal());
    }

    /**
     * 商家回复评论
     */
    @ApiOperation("商家回复评论")
    @PostMapping("/replyComment")
    public Result<Boolean> replyComment(@RequestBody OmsOrderCommentReplyForm form) {
        Boolean result = commentReplyService.replyComment(form);

        return Result.judge(result);
    }
}
